package org.laobai.meiqia.skill.controller;


import org.laobai.meiqia.common.constant.StatusCode;
import org.laobai.meiqia.common.struct.Pair;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import org.laobai.meiqia.skill.service.SkillGoodsService;
import org.laobai.meiqia.skill.entity.SkillGoods;
import org.laobai.meiqia.skill.struct.PageResult;
import org.laobai.meiqia.skill.struct.Result;
import org.laobai.meiqia.skill.vo.SearchVO;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jiusan
 * @since 2020-12-13
 */
@RestController
@RequestMapping("/skill-goods")
public class SkillGoodsController {
    @Resource
    private SkillGoodsService skillGoodsService;

    @GetMapping("/{id}")
    public Result<SkillGoods> getById(@PathVariable("id") Long id) {
        return Result.ok(skillGoodsService.detailById(id));
    }

    @GetMapping("/{userId}/{goodsId}")
    public Result<Object> preReduceStock(@PathVariable("userId") Long userId, @PathVariable("goodsId") Long skillId) {
        Pair<Integer, Object> pair = skillGoodsService.preReduceStock(userId, skillId);

        String msg = pair.getKey() == StatusCode.Skill.SUCCESS ? "" : pair.getValue().toString();

        return new Result<>(true, pair.getKey(), msg, pair.getValue());

    }

    @GetMapping
    public Result<List<SkillGoods>> list() {
        return Result.ok(skillGoodsService.list());
    }

    @PostMapping
    public Result add(@RequestBody SkillGoods skillGoods) {
        return skillGoodsService.saveSkillGoods(skillGoods) ? Result.ok() : Result.error();
    }

    @PutMapping
    public Result update(@RequestBody SkillGoods skillGoods) {
        return skillGoodsService.updateSkillGoods(skillGoods) ? Result.ok() : Result.error();
    }

    @DeleteMapping("/{id}")
    public Result delById(@PathVariable("id") Long id) {
        return skillGoodsService.delById(id) ? Result.ok() : Result.error();
    }

    @PostMapping("search/{currPage}/{pageSize}")
    public Result<PageResult<SkillGoods>> page(@PathVariable("currPage") Integer currPage,
                                               @PathVariable("pageSize") Integer pageSize,
                                               @RequestBody(required = false) SearchVO vo) {
        return Result.ok(skillGoodsService.page(currPage, pageSize, vo));
    }

    @PostMapping("delByIds")
    public Result delByIds(@RequestBody List<Long> ids) {
        return skillGoodsService.delByIds(ids) ? Result.ok() : Result.error();
    }

}
